
#include "GameLoop.h"
#include "Graphics/GraphicsBase.h"
#include "World.h"
#include "Utils/Timer.h"
#include "Input/Input.h"
#include "HUD.h"
#include "Settings.h"
#include "GameState.h"

#include <SDL/SDL.h>
#include <GL/gl.h>
#include <iostream>

void drawScene(void);
void dummyDrawScene(void);
void pollEvents(void);

static bool done = false;

static void (*drawSceneFunc) (void) = NULL;

void GameLoop::initialise(void){
    done = false;
    World::instance().load();
    if(Settings::instance().getIntValue("graphics", "render")){
        drawSceneFunc = &drawScene;
    } else {
        drawSceneFunc = &dummyDrawScene;
    }
}

void GameLoop::shutdown(void){
    World::reset();
    GameState::reset();
}

bool GameLoop::execute(void){
    unsigned frame = 0;
    while(!done){
        Timer::update();

        pollEvents();
        if(Input::instance().isKeyDownAndClear("quit")){
            done = true;
        }

        HUD::instance().update();
        World::instance().update();

//        if(Settings::instance().getIntValue("graphics", "render")){
//            drawScene();
//        }
        (*drawSceneFunc)();

        frame++;
    }

    drawSceneFunc = &dummyDrawScene;
    return true;
}


void pollEvents(void){
    SDL_Event event;

    // handle the events in the queue
    while(SDL_PollEvent(&event)){
        switch(event.type){
            case SDL_KEYDOWN:
                Input::instance().updateKey(event.key.keysym.sym, true);
                break;
            case SDL_KEYUP:
                Input::instance().updateKey(event.key.keysym.sym, false);
                break;
            case SDL_MOUSEBUTTONDOWN:
                Input::instance().updateMouseButton((int)event.button.button, true);
                break;
            case SDL_MOUSEBUTTONUP:
                Input::instance().updateMouseButton((int)event.button.button, false);
                break;
            case SDL_QUIT:
                // handle quit requests
                done = true;
                break;

            default:
                break;
        }
    }
}

void dummyDrawScene(void) {
}

void drawScene(void){
    // Clear The Screen And The Depth Buffer
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glLoadIdentity();
    
    glPushMatrix();
    glTranslatef(0.0f, 0.0f, -GraphicsBase::getCameraHeight() );

    Vector2D focus = World::instance().getCurrentFocusPoint();
    glTranslatef(-focus.x, -focus.y, 0.0f);
    World::instance().render();
    HUD::instance().renderCursor();
    glPopMatrix();

    HUD::instance().renderHUD();

    // Draw it to the screen */
    SDL_GL_SwapBuffers( );
}

